package com.ruoyi.business.modbus.service.modbus4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ruoyi.business.modbus.domain.ModbusMasterDevice;
import com.ruoyi.business.modbus.domain.ModbusReadRequest;
import com.ruoyi.business.modbus.domain.ModbusReadResponse;
import com.ruoyi.business.modbus.domain.ModbusWriteResponse;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.BatchRead;
import com.serotonin.modbus4j.BatchResults;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.code.DataType;

/**
 * Modbus4J服务抽象基类
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
public abstract class AbstractModbus4jService
{
    protected static final Logger log = LoggerFactory.getLogger(AbstractModbus4jService.class);

    // 连接池管理
    protected final Map<String, ConnectionInfo> connectionPool = new ConcurrentHashMap<>();
    private ScheduledExecutorService connectionCleanupExecutor;
    private final long IDLE_TIMEOUT_MS = 30 * 60 * 1000L; // 30分钟空闲超时
    private final long CLEANUP_INTERVAL_MINUTES = 5; // 5分钟清理间隔
    
    /**
     * 连接信息封装
     */
    protected static class ConnectionInfo {
        private final ModbusMaster master;
        private final String deviceSN;
        private final long createTime;
        private volatile long lastAccessTime;
        private volatile boolean isActive;
        
        public ConnectionInfo(ModbusMaster master, String deviceSN) {
            this.master = master;
            this.deviceSN = deviceSN;
            this.createTime = System.currentTimeMillis();
            this.lastAccessTime = System.currentTimeMillis();
            this.isActive = true;
        }
        
        public void updateAccessTime() {
            this.lastAccessTime = System.currentTimeMillis();
        }
        
        public boolean isIdle() {
            return System.currentTimeMillis() - lastAccessTime > 30 * 60 * 1000L; // 30分钟
        }
        
        public long getIdleTime() {
            return System.currentTimeMillis() - lastAccessTime;
        }
        
        // Getters
        public ModbusMaster getMaster() { return master; }
        public String getDeviceSN() { return deviceSN; }
        public long getCreateTime() { return createTime; }
        public long getLastAccessTime() { return lastAccessTime; }
        public boolean isActive() { return isActive; }
        public void setActive(boolean active) { this.isActive = active; }
    }

    /**
     * 初始化连接管理器
     */
    @PostConstruct
    protected void initConnectionManager() {
        // 启动定期清理任务
        connectionCleanupExecutor = Executors.newScheduledThreadPool(1);
        connectionCleanupExecutor.scheduleWithFixedDelay(
            this::cleanupIdleConnections, 
            CLEANUP_INTERVAL_MINUTES, 
            CLEANUP_INTERVAL_MINUTES, 
            TimeUnit.MINUTES
        );
        log.info("Modbus4J连接管理器已启动，空闲超时: {}分钟, 清理间隔: {}分钟", 
            IDLE_TIMEOUT_MS / 60000, CLEANUP_INTERVAL_MINUTES);
    }

    /**
     * 清理空闲连接
     */
    private void cleanupIdleConnections() {
        List<String> idleConnections = new ArrayList<>();
        
        for (Map.Entry<String, ConnectionInfo> entry : connectionPool.entrySet()) {
            ConnectionInfo info = entry.getValue();
            if (info.isIdle()) {
                idleConnections.add(entry.getKey());
            }
        }
        
        for (String deviceSN : idleConnections) {
            ConnectionInfo info = connectionPool.remove(deviceSN);
            if (info != null) {
                try {
                    info.getMaster().destroy();
                    log.info("清理空闲Modbus连接: 设备ID={}, 空闲时间={}分钟", 
                        deviceSN, info.getIdleTime() / 60000);
                } catch (Exception e) {
                    log.warn("清理空闲连接时出错: 设备ID={}, 错误={}", deviceSN, e.getMessage());
                }
            }
        }
        
        if (!idleConnections.isEmpty()) {
            log.debug("本次清理了 {} 个空闲连接，当前活跃连接数: {}", 
                idleConnections.size(), connectionPool.size());
        }
    }

    /**
     * 测试连接
     */
    public ModbusReadResponse<Boolean> testConnection(ModbusMasterDevice modbusMasterEntity, int slaveAddress)
    {
        ModbusMaster master = null;
        try {
            // 从连接池中获取连接，而不是重新创建
            master = getOrCreateConnection(modbusMasterEntity);
            if (master == null) {
                return ModbusReadResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
            }

            // // 尝试读取一个保持寄存器来测试连接
            // BaseLocator<Number> locator = BaseLocator.holdingRegister(
            //     slaveAddress, 
            //     0, 
            //     DataType.TWO_BYTE_INT_UNSIGNED
            // );
            // Number value = master.getValue(locator);

            // log.debug("设备 {} 连接测试成功,value={}", modbusMasterEntity.getDeviceSN(),value);
            List<Boolean> result = Arrays.asList(true);
            return ModbusReadResponse.success("连接测试成功", result, modbusMasterEntity.getDeviceSN());
            
        } catch (Exception e) {
            String errorMsg = "连接测试失败: " + e.getMessage();
            handleModbusException(e, "连接测试");
            return ModbusReadResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
        // 移除finally块，不销毁连接，让连接池管理连接的生命周期
    }

    /**
     * 读取保持寄存器
     * 0x03
     */
    public ModbusReadResponse<Integer> readHoldingRegisters(ModbusMasterDevice modbusMasterEntity,
                                                            int slaveAddress, int startAddress, int quantity)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusReadResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            BatchRead<String> batchRead = new BatchRead<>();
            
            for (int i = 0; i < quantity; i++) {
                BaseLocator<Number> locator = BaseLocator.holdingRegister(
                    slaveAddress, 
                    startAddress + i, 
                    DataType.TWO_BYTE_INT_UNSIGNED
                );
                batchRead.addLocator("register_" + (startAddress + i), locator);
            }
            
            BatchResults<String> results = master.send(batchRead);
            
            List<Integer> values = new ArrayList<>();
            for (int i = 0; i < quantity; i++) {
                Object value = results.getValue("register_" + (startAddress + i));
                if (value instanceof Number) {
                    values.add(((Number) value).intValue());
                } else {
                    throw new IllegalStateException("读取到的值类型错误，期望Number类型，实际类型: " + (value != null ? value.getClass().getSimpleName() : "null") + 
                        "，地址: " + (startAddress + i) + "，值: " + value);
                }
            }
            
            log.debug("成功读取 {} 个保持寄存器，起始地址: {}", quantity, startAddress);
            return ModbusReadResponse.success("成功读取保持寄存器", values, modbusMasterEntity.getDeviceSN());
            
        } catch (Exception e) {
            String errorMsg = "读取保持寄存器失败: " + e.getMessage();
            handleModbusException(e, "读取保持寄存器");
            return ModbusReadResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }

    /**
     * 读取输入寄存器
     * 0x04
     */
    public ModbusReadResponse<Integer> readInputRegisters(ModbusMasterDevice modbusMasterEntity,
                                                          int slaveAddress, int startAddress, int quantity)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusReadResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            BatchRead<String> batchRead = new BatchRead<>();
            
            for (int i = 0; i < quantity; i++) {
                BaseLocator<Number> locator = BaseLocator.inputRegister(
                    slaveAddress, 
                    startAddress + i, 
                    DataType.TWO_BYTE_INT_UNSIGNED
                );
                batchRead.addLocator("input_" + (startAddress + i), locator);
            }
            
            BatchResults<String> results = master.send(batchRead);
            
            List<Integer> values = new ArrayList<>();
            for (int i = 0; i < quantity; i++) {
                Object value = results.getValue("input_" + (startAddress + i));
                if (value instanceof Number) {
                    values.add(((Number) value).intValue());
                } else {
                    throw new IllegalStateException("读取到的值类型错误，期望Number类型，实际类型: " + (value != null ? value.getClass().getSimpleName() : "null") + 
                        "，地址: " + (startAddress + i) + "，值: " + value);
                }
            }
            
            log.debug("成功读取 {} 个输入寄存器，起始地址: {}", quantity, startAddress);
            return ModbusReadResponse.success("成功读取输入寄存器", values, modbusMasterEntity.getDeviceSN());
            
        } catch (Exception e) {
            String errorMsg = "读取输入寄存器失败: " + e.getMessage();
            handleModbusException(e, "读取输入寄存器");
            return ModbusReadResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }

    /**
     * 读取线圈
     * 0x01
     */
    public ModbusReadResponse<Boolean> readCoils(ModbusMasterDevice modbusMasterEntity,
                                                 int slaveAddress, int startAddress, int quantity)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusReadResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            BatchRead<String> batchRead = new BatchRead<>();
            
            for (int i = 0; i < quantity; i++) {
                BaseLocator<Boolean> locator = BaseLocator.coilStatus(
                    slaveAddress, 
                    startAddress + i
                );
                batchRead.addLocator("coil_" + (startAddress + i), locator);
            }
            
            BatchResults<String> results = master.send(batchRead);
            
            List<Boolean> values = new ArrayList<>();
            for (int i = 0; i < quantity; i++) {
                Object value = results.getValue("coil_" + (startAddress + i));
                if (value instanceof Boolean) {
                    values.add((Boolean) value);
                } else {
                    throw new IllegalStateException("读取到的值类型错误，期望Boolean类型，实际类型: " + (value != null ? value.getClass().getSimpleName() : "null") + 
                        "，地址: " + (startAddress + i) + "，值: " + value);
                }
            }
            
            log.debug("成功读取 {} 个线圈，起始地址: {}", quantity, startAddress);
            return ModbusReadResponse.success("成功读取线圈", values, modbusMasterEntity.getDeviceSN());
            
        } catch (Exception e) {
            String errorMsg = "读取线圈失败: " + e.getMessage();
            handleModbusException(e, "读取线圈");
            return ModbusReadResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }

    /**
     * 读取离散输入
     * 0x02
     */
    public ModbusReadResponse<Boolean> readDiscreteInputs(ModbusMasterDevice modbusMasterEntity,
                                                          int slaveAddress, int startAddress, int quantity)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusReadResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            BatchRead<String> batchRead = new BatchRead<>();
            
            for (int i = 0; i < quantity; i++) {
                BaseLocator<Boolean> locator = BaseLocator.inputStatus(
                    slaveAddress, 
                    startAddress + i
                );
                batchRead.addLocator("discrete_" + (startAddress + i), locator);
            }
            
            BatchResults<String> results = master.send(batchRead);
            
            List<Boolean> values = new ArrayList<>();
            for (int i = 0; i < quantity; i++) {
                Object value = results.getValue("discrete_" + (startAddress + i));
                if (value instanceof Boolean) {
                    values.add((Boolean) value);
                } else {
                    throw new IllegalStateException("读取到的值类型错误，期望Boolean类型，实际类型: " + (value != null ? value.getClass().getSimpleName() : "null") + 
                        "，地址: " + (startAddress + i) + "，值: " + value);
                }
            }
            
            log.debug("成功读取 {} 个离散输入，起始地址: {}", quantity, startAddress);
            return ModbusReadResponse.success("成功读取离散输入", values, modbusMasterEntity.getDeviceSN());
            
        } catch (Exception e) {
            String errorMsg = "读取离散输入失败: " + e.getMessage();
            handleModbusException(e, "读取离散输入");
            return ModbusReadResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }

    /**
     * 写入单个线圈
     * 0x05
     */
    public ModbusWriteResponse writeSingleCoil(ModbusMasterDevice modbusMasterEntity,
                                               int slaveAddress, int address, boolean value,
                                               boolean verify)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusWriteResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            BaseLocator<Boolean> locator = BaseLocator.coilStatus(slaveAddress, address);
            master.setValue(locator, value);
            
            log.debug("成功写入线圈，地址: {}, 值: {}", address, value);
            
            // 如果需要验证，则读取验证
            if (verify) {
                try {
                    // 等待一小段时间让设备稳定
                    Thread.sleep(50);
                    
                    // 读取验证
                    Boolean actualValue = master.getValue(locator);
                    
                    // 检查值是否匹配
                    if (actualValue != null && actualValue.equals(value)) {
                        log.debug("线圈写入验证成功，地址: {}, 值: {}", address, actualValue);
                        List<Boolean> result = Arrays.asList(true);
                        return ModbusWriteResponse.success("成功写入并验证线圈", modbusMasterEntity.getDeviceSN());
                    } else {
                        String errorMsg = String.format("线圈写入验证失败: 期望值=%s, 实际值=%s", value, actualValue);
                        log.warn(errorMsg);
                        return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                    }
                } catch (Exception e) {
                    String errorMsg = "线圈写入验证失败: " + e.getMessage();
                    log.warn(errorMsg);
                    return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                }
            } else {
                List<Boolean> result = Arrays.asList(true);
                return ModbusWriteResponse.success("成功写入线圈", modbusMasterEntity.getDeviceSN());
            }
            
        } catch (Exception e) {
            String errorMsg = "写入单个线圈失败: " + e.getMessage();
            handleModbusException(e, "写入单个线圈");
            return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }

    /**
     * 写入多个线圈
     * 0x0F
     */
    public ModbusWriteResponse writeMultipleCoils(ModbusMasterDevice modbusMasterEntity,
                                                  int slaveAddress, int startAddress, List<Boolean> values,
                                                  boolean verify)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusWriteResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            for (int i = 0; i < values.size(); i++) {
                BaseLocator<Boolean> locator = BaseLocator.coilStatus(slaveAddress, startAddress + i);
                master.setValue(locator, values.get(i));
            }
            
            log.debug("成功写入 {} 个线圈，起始地址: {}", values.size(), startAddress);
            
            // 如果需要验证，则读取验证
            if (verify) {
                try {
                    // 等待一小段时间让设备稳定
                    Thread.sleep(50);
                    
                    // 验证所有写入的值
                    boolean allMatch = true;
                    StringBuilder mismatchInfo = new StringBuilder();
                    
                    for (int i = 0; i < values.size(); i++) {
                        BaseLocator<Boolean> locator = BaseLocator.coilStatus(slaveAddress, startAddress + i);
                        Boolean actualValue = master.getValue(locator);
                        Boolean expectedValue = values.get(i);
                        
                        if (!expectedValue.equals(actualValue)) {
                            allMatch = false;
                            mismatchInfo.append(String.format("地址%d: 期望=%s, 实际=%s; ", startAddress + i, expectedValue, actualValue));
                        }
                    }
                    
                    if (allMatch) {
                        log.debug("线圈批量写入验证成功，起始地址: {}, 数量: {}", startAddress, values.size());
                        List<Boolean> result = Arrays.asList(true);
                        return ModbusWriteResponse.success(String.format("成功写入并验证%d个线圈", values.size()), modbusMasterEntity.getDeviceSN());
                    } else {
                        String errorMsg = "线圈批量写入验证失败: " + mismatchInfo.toString();
                        log.warn(errorMsg);
                        return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                    }
                } catch (Exception e) {
                    String errorMsg = "线圈批量写入验证失败: " + e.getMessage();
                    log.warn(errorMsg);
                    return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                }
            } else {
                List<Boolean> result = Arrays.asList(true);
                return ModbusWriteResponse.success("成功写入多个线圈", modbusMasterEntity.getDeviceSN());
            }
            
        } catch (Exception e) {
            String errorMsg = "写入多个线圈失败: " + e.getMessage();
            handleModbusException(e, "写入多个线圈");
            return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }

    /**
     * 写入单个寄存器
     * 0x06
     */
    public ModbusWriteResponse writeSingleRegister(ModbusMasterDevice modbusMasterEntity,
                                                   int slaveAddress, int address, int value,
                                                   boolean verify)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusWriteResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            BaseLocator<Number> locator = BaseLocator.holdingRegister(slaveAddress, address, DataType.TWO_BYTE_INT_UNSIGNED);
            master.setValue(locator, value);
            
            log.debug("成功写入寄存器，地址: {}, 值: {}", address, value);
            
            // 如果需要验证，则读取验证
            if (verify) {
                try {
                    // 等待一小段时间让设备稳定
                    Thread.sleep(50);
                    
                    // 读取验证
                    Number actualValue = master.getValue(locator);
                    
                    // 检查值是否匹配
                    if (actualValue != null && actualValue.intValue() == value) {
                        log.debug("寄存器写入验证成功，地址: {}, 值: {}", address, actualValue);
                        List<Boolean> result = Arrays.asList(true);
                        return ModbusWriteResponse.success("成功写入并验证寄存器", modbusMasterEntity.getDeviceSN());
                    } else {
                        String errorMsg = String.format("寄存器写入验证失败: 期望值=%s, 实际值=%s", value, actualValue);
                        log.warn(errorMsg);
                        return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                    }
                } catch (Exception e) {
                    String errorMsg = "寄存器写入验证失败: " + e.getMessage();
                    log.warn(errorMsg);
                    return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                }
            } else {
                List<Boolean> result = Arrays.asList(true);
                return ModbusWriteResponse.success("成功写入寄存器", modbusMasterEntity.getDeviceSN());
            }
            
        } catch (Exception e) {
            String errorMsg = "写入单个寄存器失败: " + e.getMessage();
            handleModbusException(e, "写入单个寄存器");
            return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }

    /**
     * 写入多个寄存器
     * 0x10
     */
    public ModbusWriteResponse writeMultipleRegisters(ModbusMasterDevice modbusMasterEntity,
                                                      int slaveAddress, int startAddress, List<Integer> values,
                                                      boolean verify)
    {
        ModbusMaster master = getOrCreateConnection(modbusMasterEntity);
        if (master == null) {
            return ModbusWriteResponse.failure("无法获取Modbus连接: 连接池创建连接失败", modbusMasterEntity.getDeviceSN());
        }

        try {
            for (int i = 0; i < values.size(); i++) {
                BaseLocator<Number> locator = BaseLocator.holdingRegister(slaveAddress, startAddress + i, DataType.TWO_BYTE_INT_UNSIGNED);
                master.setValue(locator, values.get(i));
            }
            
            log.debug("成功写入 {} 个寄存器，起始地址: {}", values.size(), startAddress);
            
            // 如果需要验证，则读取验证
            if (verify) {
                try {
                    // 等待一小段时间让设备稳定
                    Thread.sleep(50);
                    
                    // 验证所有写入的值
                    boolean allMatch = true;
                    StringBuilder mismatchInfo = new StringBuilder();
                    
                    for (int i = 0; i < values.size(); i++) {
                        BaseLocator<Number> locator = BaseLocator.holdingRegister(slaveAddress, startAddress + i, DataType.TWO_BYTE_INT_UNSIGNED);
                        Number actualValue = master.getValue(locator);
                        Integer expectedValue = values.get(i);
                        
                        if (actualValue == null || actualValue.intValue() != expectedValue) {
                            allMatch = false;
                            mismatchInfo.append(String.format("地址%d: 期望=%s, 实际=%s; ", startAddress + i, expectedValue, actualValue));
                        }
                    }
                    
                    if (allMatch) {
                        log.debug("寄存器批量写入验证成功，起始地址: {}, 数量: {}", startAddress, values.size());
                        List<Boolean> result = Arrays.asList(true);
                        return ModbusWriteResponse.success(String.format("成功写入并验证%d个寄存器", values.size()), modbusMasterEntity.getDeviceSN());
                    } else {
                        String errorMsg = "寄存器批量写入验证失败: " + mismatchInfo.toString();
                        log.warn(errorMsg);
                        return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                    }
                } catch (Exception e) {
                    String errorMsg = "寄存器批量写入验证失败: " + e.getMessage();
                    log.warn(errorMsg);
                    return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
                }
            } else {
                List<Boolean> result = Arrays.asList(true);
                return ModbusWriteResponse.success("成功写入多个寄存器", modbusMasterEntity.getDeviceSN());
            }
            
        } catch (Exception e) {
            String errorMsg = "写入多个寄存器失败: " + e.getMessage();
            handleModbusException(e, "写入多个寄存器");
            return ModbusWriteResponse.failure(errorMsg, modbusMasterEntity.getDeviceSN());
        }
    }


    /**
     * 获取连接状态
     */
    public boolean getConnectionStatus(String deviceSN)
    {
        ConnectionInfo info = connectionPool.get(deviceSN);
        return info != null && info.isActive() && info.getMaster() != null;
    }

    /**
     * 关闭指定设备的连接
     */
    protected void closeConnection(String deviceSN)
    {
        ConnectionInfo info = connectionPool.remove(deviceSN);
        if (info != null) {
            try {
                info.getMaster().destroy();
                info.setActive(false);
                log.debug("已关闭设备 {} 的连接", deviceSN);
            } catch (Exception e) {
                log.warn("关闭设备 {} 连接时出错: {}", deviceSN, e.getMessage());
            }
        }
    }

    /**
     * 程序退出时自动关闭所有连接
     */
    @PreDestroy
    private void closeAllConnections()
    {
        log.info("程序退出，开始关闭Modbus4J连接管理器...");
        
        // 先关闭清理任务
        if (connectionCleanupExecutor != null && !connectionCleanupExecutor.isShutdown()) {
            connectionCleanupExecutor.shutdown();
            try {
                if (!connectionCleanupExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
                    connectionCleanupExecutor.shutdownNow();
                    log.warn("强制关闭连接清理任务");
                }
            } catch (InterruptedException e) {
                connectionCleanupExecutor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
        
        if (connectionPool.isEmpty()) {
            log.info("没有活跃的Modbus连接需要关闭");
            return;
        }
        
        log.info("开始关闭所有Modbus连接，共 {} 个连接", connectionPool.size());
        
        for (Map.Entry<String, ConnectionInfo> entry : connectionPool.entrySet()) {
            try {
                ConnectionInfo info = entry.getValue();
                if (info != null && info.getMaster() != null) {
                    info.getMaster().destroy();
                    info.setActive(false);
                    log.debug("已关闭设备 {} 的连接", entry.getKey());
                }
            } catch (Exception e) {
                log.warn("关闭设备 {} 连接时出错: {}", entry.getKey(), e.getMessage());
            }
        }
        connectionPool.clear();
        log.info("Modbus4J连接管理器已关闭，所有连接已清理");
    }

    /**
     * 获取设备统计信息
     */
    public Map<String, Object> getDeviceStatistics(ModbusMasterDevice modbusMasterEntity)
    {
        boolean isConnected = getConnectionStatus(modbusMasterEntity.getDeviceSN());
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("deviceSN", modbusMasterEntity.getDeviceSN());
        stats.put("deviceName", modbusMasterEntity.getDeviceSN());
        stats.put("deviceType", modbusMasterEntity.getDeviceType());
        stats.put("timeout", modbusMasterEntity.getTimeout());
        stats.put("retries", modbusMasterEntity.getRetries());
        stats.put("connected", isConnected);
        
        return stats;
    }

    /**
     * 获取连接池统计信息
     */
    public Map<String, Object> getConnectionPoolStatistics()
    {
        int totalConnections = connectionPool.size();
        long activeConnections = connectionPool.values().stream()
                .filter(info -> info.isActive() && info.getMaster() != null)
                .count();
        long idleConnections = connectionPool.values().stream()
                .filter(ConnectionInfo::isIdle)
                .count();
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalConnections", totalConnections);
        stats.put("activeConnections", activeConnections);
        stats.put("idleConnections", idleConnections);
        stats.put("connectionIds", new ArrayList<>(connectionPool.keySet()));
        stats.put("idleTimeoutMinutes", IDLE_TIMEOUT_MS / 60000);
        stats.put("cleanupIntervalMinutes", CLEANUP_INTERVAL_MINUTES);
        
        // 连接详情
        List<Map<String, Object>> connectionDetails = new ArrayList<>();
        for (Map.Entry<String, ConnectionInfo> entry : connectionPool.entrySet()) {
            ConnectionInfo info = entry.getValue();
            Map<String, Object> detail = new HashMap<>();
            detail.put("deviceSN", info.getDeviceSN());
            detail.put("createTime", info.getCreateTime());
            detail.put("lastAccessTime", info.getLastAccessTime());
            detail.put("idleTime", info.getIdleTime());
            detail.put("isActive", info.isActive());
            detail.put("isIdle", info.isIdle());
            connectionDetails.add(detail);
        }
        stats.put("connectionDetails", connectionDetails);
        
        return stats;
    }

    /**
     * 获取或创建连接
     */
    protected ModbusMaster getOrCreateConnection(ModbusMasterDevice modbusMasterEntity)
    {
        String deviceSN = modbusMasterEntity.getDeviceSN();
        ConnectionInfo info = connectionPool.get(deviceSN);
        
        // 如果连接存在且活跃，更新访问时间并返回
        if (info != null && info.isActive() && info.getMaster() != null) {
            info.updateAccessTime();
            return info.getMaster();
        }
        
        // 创建新连接
        try {
            ModbusMaster master = createModbusMaster(modbusMasterEntity);
            if (master != null) {
                ConnectionInfo newInfo = new ConnectionInfo(master, deviceSN);
                connectionPool.put(deviceSN, newInfo);
                log.debug("为设备 {} 创建新Modbus连接，当前连接池大小: {}", deviceSN, connectionPool.size());
                return master;
            }
        } catch (Exception e) {
            log.error("为设备 {} 创建Modbus连接失败: {}", deviceSN, e.getMessage());
        }
        
        return null;
    }

    /**
     * 创建Modbus主站 - 子类必须实现
     */
    protected abstract ModbusMaster createModbusMaster(ModbusMasterDevice modbusMasterEntity) throws Exception;

    /**
     * 处理Modbus异常
     */
    protected void handleModbusException(Exception e, String operation) {
        log.error("Modbus操作失败 [{}]: {}", operation, e.getMessage(), e);
    }
}
